// miniprogram/pages/detail/detail.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAuthor: null, // 当前用户是否为作者
    isAccepted: false, // 对方是否接受了申请或线索
    noticeId: '', // 公告id
    notice: null, // 公告数据
    displayType: '', // 标题 - 公告类型
    displayClasses: '', // 标题 - 类别
    displayAddress: '', // 地址
    displayImages: [],
    requestsName: '申请', // 申请的名称：申请或线索
    requestsTitle: '我的申请',
    requests: null // 收到的申请
  },

  /**
   * 获取公告数据
   */
  queryNotice () {
    wx.showLoading({ title: '加载中' })
    const id = this.data.noticeId
    wx.cloud.callFunction({
      name: 'queryNoticeById',
      data: { id }
    }).then(res => {
      const { code, data, isAuthor } = res.result
      if (code === 0) {
        // 设置详情显示内容
        data.time = app.formatDate(data.time, 'date')
        const displayType = data.type === 0 ? '招领启事'
            : data.classes[0] === '男性' || data.classes[0] === '女性'
            ? '寻人启事' : '寻物启事'
        const requestsName = data.type === 0 ? '申请' : '线索'
        this.setData({
          isAuthor,
          notice: data,
          displayType,
          requestsName,
          requestsTitle: isAuthor ? `收到的${requestsName}` : `我的${requestsName}`,
          displayClasses: data.classes.join(' - '),
          displayAddress: data.region.join('') + data.address,
          displayImages: [data.image].concat(data.detail_images)
        })
      }
    }).catch(res => {
      wx.switchTab({
        url: '/pages/home/home'
      })
    }).finally(() => {
      wx.hideLoading()
    })
  },

  /**
   * 获取收到的申请或线索
   */
  queryRequests () {
    wx.showLoading({ title: '加载中' })
    const noticeId = this.data.noticeId
    wx.cloud.callFunction({
      name: 'queryRequestOfNotice',
      data: { noticeId }
    }).then(res => {
      const { errMsg, data } = res.result
      if (errMsg === 'collection.get:ok') {
        const index = data.findIndex(v => v.status === 1)
        this.setData({ requests: data, isAccepted: index >= 0 })
      }
    }).finally(() => {
      wx.hideLoading()
    })
  },

  /**
   * 查看大图
   */
  bindViewImages (event) {
    const index = event.target.dataset.index
    wx.previewImage({
      urls: this.data.displayImages,
      current: index
    })
  },

  /**
   * 提交申请或线索
   */
  bindRequest () {
    const requests = this.data.requests
    if (requests.length >= 3) {
      wx.showToast({
        title: '最多只能提交三次!'
      })
    } else {
      const type = this.data.notice.type
      const notice = this.data.notice._id
      const receiver = this.data.notice._openid
      wx.navigateTo({
        url: `/pages/request/request?type=${type}&notice=${notice}&receiver=${receiver}`
      })
    }
  },

  /**
   * 编辑公告
   */
  bindEdit () {
    const notice = this.data.notice
    wx.navigateTo({
      url: `/pages/editor/editor?id=${notice._id}`,
      success (res) {
        res.eventChannel.emit('editNotice', { data: notice })
      }
    })
  },

  /**
   * 关闭公告
   */
  bindClose () {
    const _this = this
    const id = this.data.notice._id
    wx.showModal({
      content: '确定关闭此公告吗？',
      success (res) {
        if (res.confirm) {
          wx.showLoading({ title: '提交中' })
          wx.cloud.callFunction({
            name: 'updateNotice',
            data: { operation: 'close', id }
          }).then(res => {
            if (res.result.errMsg === 'document.update:ok') {
              wx.showToast({
                type: 'success',
                title: '操作成功'
              })
              _this.setData({ 'notice.status': 0 })
            } else {
              wx.showToast({ title: '操作失败' })
            }
          }).catch(err => {
            wx.showToast({ title: '操作失败' })
          })
        }
      }
    })
  },

  /**
   * 联系对方
   */
  bindCall() {
    if (this.data.isAccepted) {
      wx.makePhoneCall({
        phoneNumber: this.data.notice.phone
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.noticeId = options.id
    this.queryNotice()
    this.queryRequests()
    // 设置分享按钮
    wx.showShareMenu({
      // withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 转发给朋友
   * @param {Object} res 
   */
  onShareAppMessage (res) {
    const notice = this.data.notice
    const requestType = notice.type === 0 ? '招领启事'
      : notice.classes[0] === '男性' || notice.classes[0] === '女性'
      ? '寻人启事' : '寻物启事'
    return {
      title: `【${requestType}】${notice.title}`,
      imageUrl: notice.image
    }
  },

  /**
   * 分享到朋友圈
   * @param {Object} res 
   */
  onShareTimeline (res) {
    const notice = this.data.notice
    const requestType = notice.type === 0 ? '招领启事'
      : notice.classes[0] === '男性' || notice.classes[0] === '女性'
      ? '寻人启事' : '寻物启事'
    return {
      title: `【${requestType}】${notice.title}`,
      imageUrl: notice.image
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})